#
# messkit.async
#
# Copyright 2006 Helsinki Institute for Information Technology (HIIT)
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Worker thread abstraction

This defines a Thread class that runs as a daemon thread
automatically, without having to be started explicitly, and
executes function calls queued using the async() method.
"""

from Queue import Queue
import threading

class ThreadExit(Exception):
    """
    Thread exit exception

    Functions executed by a Thread instance can raise ThreadExit
    to cause the thread to terminate immediately.
    """
    pass

class Thread(threading.Thread):
    """
    Worker thread
    """
    def __init__(self, name=None):
        """
        Initialize a Thread instance.

        It will immediately begin waiting for work to be queued using
        the async() method.  It will run as a daemon thread.
        """
        threading.Thread.__init__(self, name=name)
        self.queue = Queue()
        self.setDaemon(True)
        self.start()

    def async(self, f, *params, **options):
        """
        Queue a function call for execution.
        """
        self.queue.put(lambda: f(*params, **options))

    def terminate(self, timeout=0):
        """
        Queue a command for the thread to exit.

        If a non-zero timeout is specified, wait that long for the
        thread to actually exit.  If the timeout is None, wait for as
        long as necessary.
        """
        def die():
            raise ThreadExit

        self.async(die)
        if timeout != 0:
            self.join(timeout)

    def run(self):
        try:
            while True:
                f = self.queue.get()
                f()
        except ThreadExit:
            pass
